package com.phpxiu.app.view;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.LiveHistoryContent;
import com.phpxiu.app.model.ShareContent;
import com.phpxiu.app.model.event.WeiXinEvent;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.custom.FrescoImageView;
import com.phpxiu.app.view.dialog.HVShareMenus;

import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;


/**
 * Created by 吴金洲 on 2016/10/22
 */
public class UIHistoryVideoPlayer extends BaseShare implements SeekBar.OnSeekBarChangeListener,View.OnClickListener
        ,MediaPlayer.OnPreparedListener
        ,MediaPlayer.OnCompletionListener
        ,MediaPlayer.OnErrorListener{
    public final static String LIVE_INFO="live_history_info";
    private ForegroundColorSpan TICKETS_SPAN=new ForegroundColorSpan(Color.parseColor("#ff24A8DF"));
    private final static int UPDATE_PRO=0x11;
    private LiveHistoryContent mLiveInfo;
    private View loadingView;
    private AnimationDrawable loadingAnim;
    private FrescoImageView bgView;
    private FrescoImageView avatarView;
    private TextView watchCountView;
    private TextView liveNoView;
    private TextView ticketView;
    private TextView durationStepView;
    private SeekBar mSeekBar;
    private VideoView mVideoView;
    private long duration=0;//总时长
    private long playPosition=0;//当前播放点
    private String durationTime="00:00:00";
    private String durationSplit=":";
    private Timer timer;//更新进度定时器、每秒更新一次
    private TimerTask updateTask;//更新进度任务、每秒执行一次
    private String ticketLabel;
    private SpannableStringBuilder ticketsCountText=new SpannableStringBuilder();
    private ImageButton playBtn;
    private boolean isPause=false;
    private boolean isPrepare=false;//已准备就绪

    private HVShareMenus shareMenus;
    public ShareContent shareContent=null;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        try {
            mLiveInfo=(LiveHistoryContent)getIntent().getSerializableExtra(LIVE_INFO);
        }catch (Exception e){
            e.printStackTrace();
        }
        KKYUtil.log("播放地址：" + mLiveInfo);
        if(mLiveInfo==null){
            finish();
            return;
        }
        ticketLabel=getString(R.string.ui_room_card_tickets_label);
        shareContent=new ShareContent(this);
        shareContent.setTitle(mLiveInfo.getNick());
        shareContent.setSummary(mLiveInfo.getNick());
        shareContent.setImageUrl(mLiveInfo.getAvatar());
        shareContent.setTargetUrl(HttpConfig.SHARE_URL+mLiveInfo.getHostId());
        setContentView(R.layout.ui_history_video_player);
        init();
    }

    /**
     * 初始化
     */
    private void init(){
        bgView=(FrescoImageView)findViewById(R.id.avatar_bg_view);
        bgView.setImageURI(Uri.parse(mLiveInfo.getAvatar()));
        avatarView=(FrescoImageView)findViewById(R.id.head_view);
        avatarView.setOnClickListener(this);
        avatarView.setImageURI(Uri.parse(mLiveInfo.getAvatar()));
        watchCountView=(TextView)findViewById(R.id.watch_count_info);
        watchCountView.setText(mLiveInfo.getWatchCount());
        ticketView=(TextView)findViewById(R.id.tickets_count_view);
        ticketsCountText.clear();
        ticketsCountText.append(ticketLabel).append(" "+mLiveInfo.getTickets());
        ticketsCountText.setSpan(TICKETS_SPAN,ticketLabel.length(),ticketsCountText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ticketView.setText(ticketsCountText);
        liveNoView=(TextView)findViewById(R.id.live_no_view);
        liveNoView.setText("ID "+ mLiveInfo.getLiveNo());
        mVideoView=(VideoView)findViewById(R.id.player_view);
        mVideoView.getHolder().setFixedSize((int)KKYApp.screenWidth,(int)KKYApp.screenHeight);
        mVideoView.setOnPreparedListener(this);
        mVideoView.setOnErrorListener(this);
        mVideoView.setOnCompletionListener(this);
        mVideoView.setVideoURI(Uri.parse(mLiveInfo.getVideoUrl()));
        loadingView=findViewById(R.id.loadingImageView);
        loadingAnim=(AnimationDrawable)loadingView.getBackground();
        if(loadingView!=null&&loadingView.getVisibility()!=View.VISIBLE){
            loadingView.setVisibility(View.VISIBLE);
        }
        if(loadingAnim!=null){
            loadingAnim.start();
        }
        durationStepView=(TextView)findViewById(R.id.duration_step_view);
        mSeekBar = (SeekBar) findViewById(R.id.video_player_seek_bar);
        mSeekBar.setOnSeekBarChangeListener(this);
        playBtn=(ImageButton)findViewById(R.id.play_btn);
        playBtn.setOnClickListener(this);
        findViewById(R.id.exit_btn).setOnClickListener(this);
        findViewById(R.id.share_menus_btn).setOnClickListener(this);
        findViewById(R.id.rank_link).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.exit_btn:
                onBackPressed();
                break;
            case R.id.head_view:
                Intent home=new Intent(this, UserHome.class);
                home.putExtra(UserHome.EXTRA_PARAM_KEY_UID,mLiveInfo.getHostId());
                startActivity(home);
                break;
            case R.id.rank_link:
                Intent rank=new Intent(this, RoomFansRank.class);
                rank.putExtra(RoomFansRank.EXTRA_PARAM_USER_ID_KEY,mLiveInfo.getHostId());
                rank.putExtra(RoomFansRank.EXTRA_PARAM_USER_TICKETS_KEY,mLiveInfo.getTickets());
                startActivity(rank);
                break;
            case R.id.play_btn:
                if(!isPrepare){
                    return;
                }
                if(isPause){
                    playBtn.setImageResource(R.mipmap.history_video_pause_btn);
                    mVideoView.start();
                    isPause=false;
                }else{
                    playBtn.setImageResource(R.mipmap.history_video_play_btn);
                    mVideoView.pause();
                    isPause=true;
                }
                break;
            case R.id.share_menus_btn:
                showShareMenus();
                break;
        }
    }

    private void showShareMenus(){
        if(shareMenus==null){
            shareMenus=new HVShareMenus(this);
            shareMenus.getWindow().getAttributes().width=(int)KKYApp.screenWidth;
        }
        shareMenus.show(this);
    }

    /**
     * 微信分享完毕
     */
    @Subscribe
    public void onWXShare(WeiXinEvent event){
        if(WeiXinEvent.SHARE==event.getCode()){
            onPlatformShareBack(PLATFORM_WX);
        }
    }

    @Override
    public void handleMsg(Message msg) {
        super.handleMsg(msg);
        switch (msg.what){
            case UPDATE_PRO:
                updateProgress();
                break;
            default:
                break;
        }
    }

    /**
     * 播放器准备就绪
     * @param mp
     */
    @Override
    public void onPrepared(MediaPlayer mp) {
        mVideoView.start();
        isPause=false;
        playBtn.setImageResource(R.mipmap.history_video_pause_btn);
        isPrepare=true;
        if(timer!=null){
            timer.cancel();
            timer=null;
        }
        if(updateTask!=null){
            updateTask.cancel();
            updateTask=null;
        }
        handler.removeMessages(UPDATE_PRO);
        duration=mVideoView.getDuration();
        if(duration==0){
            return;
        }
        durationTime= KKYUtil.dateFormatHMS(duration, durationSplit, durationSplit, "");
        if(playPosition!=0){
            seekToPosition(playPosition);
        }
        timer=new Timer(true);
        updateTask=new TimerTask() {
            @Override
            public void run() {
                if(duration!=0){
                    if(isPrepare){
                        handler.sendEmptyMessage(UPDATE_PRO);
                    }
                }
            }
        };
        timer.schedule(updateTask,0,1000);
        if(bgView!=null&&bgView.getVisibility()==View.VISIBLE){
            bgView.setVisibility(View.INVISIBLE);
        }
        if(loadingView!=null&&loadingView.getVisibility()==View.VISIBLE){
            loadingView.setVisibility(View.INVISIBLE);
        }
        if(loadingAnim!=null){
            loadingAnim.stop();
        }
    }

    /**
     * 移动到个进度
     * @param progress
     */
    public void seekToProgress(int progress){
        long position = progress * duration / 100;
        Log.i("", "进度跳转点：" + position);
        seekToPosition(position);
    }

    /**
     * 滑到某个位置
     * @param position
     */
    public void seekToPosition(long position){
        if(mVideoView==null){
            return;
        }
        mVideoView.seekTo((int)position);
    }
    /**
     * 更新进度
     */
    public synchronized void updateProgress(){
        if(mVideoView==null){
            return;
        }
        if(duration==0){
            return;
        }
        long currentPosition=mVideoView.getCurrentPosition();
        if (currentPosition > 0) {
            int progress = (int)(currentPosition * 100 / duration);
            KKYUtil.log("当前播放时间点：" + currentPosition);
            String time= KKYUtil.dateFormatHMS(currentPosition, durationSplit, durationSplit, "");
            String step=time+"/"+durationTime;
            KKYUtil.log(progress + "-播放时间：" + step);
            durationStepView.setText(step);
            mSeekBar.setProgress(progress);
        }
    }

    /**
     * 播放出错
     * @param mp
     * @param what
     * @param extra
     * @return
     */
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        KKYUtil.log("视频播放出错:" + what + "--" + extra);
        if(KKYUtil.DEBUG){
            Toast.makeText(this,"MediaPlayer Err:"+what+"--"+extra,Toast.LENGTH_LONG).show();
        }
        finish();
        return false;
    }

    /**
     * 播放结束
     * @param mp
     */
    @Override
    public void onCompletion(MediaPlayer mp) {
        if(mVideoView!=null){
            if(KKYUtil.DEBUG){
                Toast.makeText(this,"Video Completed!",Toast.LENGTH_LONG).show();
            }
            mSeekBar.setProgress(100);
            mVideoView.seekTo(0);
        }
    }


    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser) {//用户滑动进度条时，更新播放器的进度读取
            seekToProgress(progress);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        //隐藏控制栏的消息清除
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        //停止滑动进条n秒后隐藏控制栏
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(mVideoView!=null){
            mVideoView.resume();
        }
    }

    @Override
    protected void onPause() {
        isPrepare=false;
        playPosition=mVideoView.getCurrentPosition();
        if(mVideoView!=null){
            mVideoView.pause();
            isPause=true;
            playBtn.setImageResource(R.mipmap.history_video_play_btn);
        }
        if(timer!=null){
            timer.cancel();
            timer=null;
        }
        if(updateTask!=null){
            updateTask.cancel();
            updateTask=null;
        }
        if(bgView!=null&&bgView.getVisibility()!=View.VISIBLE){
            bgView.setVisibility(View.VISIBLE);
        }
        if(loadingView!=null&&loadingView.getVisibility()!=View.VISIBLE){
            loadingView.setVisibility(View.VISIBLE);
        }
        if(loadingAnim!=null){
            loadingAnim.start();
        }
        super.onPause();
    }

    /**
     * 释放资源
     */
    private void release(){
        try {
            if(mVideoView!=null){
                if(mVideoView.isPlaying()){
                    mVideoView.stopPlayback();
                }
            }
            if(timer!=null){
                timer.cancel();
                timer=null;
            }
            if(updateTask!=null){
                updateTask.cancel();
                updateTask=null;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void finish() {
        if(shareContent!=null){
            shareContent.release();
        }
        release();
        super.finish();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        if(shareContent!=null){
            shareContent.release();
        }
        release();
        super.onDestroy();
    }

}
